import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Button, Space, Modal, Form, Input, InputNumber, DatePicker, message, Popconfirm, Select, Tag, Descriptions, Badge, Statistic, Row, Col, Progress } from 'antd';
import { SyncOutlined, EyeOutlined, CheckOutlined, CloseOutlined, CheckCircleOutlined, ExportOutlined, DollarOutlined, UserOutlined } from '@ant-design/icons';
import { request } from 'umi';
import moment from 'moment';

const { RangePicker } = DatePicker;
const { TextArea } = Input;
const { Option } = Select;

const DouyinOrder = () => {
  const [loading, setLoading] = useState(false);
  const [syncLoading, setSyncLoading] = useState(false);
  const [data, setData] = useState([]);
  const [total, setTotal] = useState(0);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [detailVisible, setDetailVisible] = useState(false);
  const [currentOrder, setCurrentOrder] = useState(null);
  const [douyinConfigs, setDouyinConfigs] = useState([]);
  const [douyinGroups, setDouyinGroups] = useState([]);
  const [filters, setFilters] = useState({
    store_id: undefined,
    douyin_id: undefined,
    douyin_group_id: undefined,
    status: undefined,
    process_status: undefined,
    is_processed: undefined,
    is_used: undefined,
    timeRange: undefined,
  });

  // 获取抖音配置列表
  const fetchDouyinConfigs = async () => {
    try {
      const response = await request('/api/v1/douyin', {
        method: 'GET',
        params: {
          page: 1,
          pageSize: 100,
        },
      });
      if (response.code === 200) {
        setDouyinConfigs(response.data.list);
      }
    } catch (error) {
      message.error('获取抖音配置列表失败');
    }
  };

  // 获取抖音团购活动列表
  const fetchDouyinGroups = async (douyinId) => {
    try {
      const response = await request('/api/v1/douyin/group', {
        method: 'GET',
        params: {
          page: 1,
          pageSize: 100,
          douyin_id: douyinId,
        },
      });
      if (response.code === 200) {
        setDouyinGroups(response.data.list);
      }
    } catch (error) {
      message.error('获取抖音团购活动列表失败');
    }
  };

  // 获取抖音团购订单列表
  const fetchList = async (page = current, size = pageSize) => {
    setLoading(true);
    try {
      const params = {
        page,
        pageSize: size,
        ...filters,
      };
      
      // 处理时间范围
      if (filters.timeRange && filters.timeRange.length === 2) {
        params.start_time = filters.timeRange[0].valueOf();
        params.end_time = filters.timeRange[1].valueOf();
      }
      
      const response = await request('/api/v1/douyin/group/order', {
        method: 'GET',
        params,
      });
      
      if (response.code === 200) {
        setData(response.data.list);
        setTotal(response.data.total);
      } else {
        message.error(response.msg || '获取抖音团购订单列表失败');
      }
    } catch (error) {
      message.error('获取抖音团购订单列表失败');
    }
    setLoading(false);
  };

  // 初始加载
  useEffect(() => {
    fetchDouyinConfigs();
    fetchList();
  }, []);

  // 处理抖音配置变化
  const handleDouyinConfigChange = (value) => {
    setFilters({
      ...filters,
      douyin_id: value,
      douyin_group_id: undefined,
    });
    fetchDouyinGroups(value);
  };

  // 处理筛选条件变化
  const handleFilterChange = (changedValues) => {
    setFilters({
      ...filters,
      ...changedValues,
    });
  };

  // 处理表格分页变化
  const handleTableChange = (pagination) => {
    setCurrent(pagination.current);
    setPageSize(pagination.pageSize);
    fetchList(pagination.current, pagination.pageSize);
  };

  // 查看订单详情
  const showDetail = async (id) => {
    try {
      const response = await request(`/api/v1/douyin/group/order/${id}`, {
        method: 'GET',
      });
      
      if (response.code === 200) {
        setCurrentOrder(response.data);
        setDetailVisible(true);
      } else {
        message.error(response.msg || '获取订单详情失败');
      }
    } catch (error) {
      message.error('获取订单详情失败');
    }
  };

  // 处理订单
  const handleProcess = async (id, status) => {
    try {
      const response = await request(`/api/v1/douyin/group/order/${id}/process`, {
        method: 'POST',
        data: { status },
      });
      
      if (response.code === 200) {
        message.success('处理成功');
        fetchList();
      } else {
        message.error(response.msg || '处理失败');
      }
    } catch (error) {
      message.error('处理失败');
    }
  };

  // 使用团购券
  const handleUse = async (id) => {
    try {
      const response = await request(`/api/v1/douyin/group/order/${id}/use`, {
        method: 'POST',
      });
      
      if (response.code === 200) {
        message.success('使用成功');
        fetchList();
      } else {
        message.error(response.msg || '使用失败');
      }
    } catch (error) {
      message.error('使用失败');
    }
  };

  // 同步订单
  const handleSync = async () => {
    if (!filters.store_id) {
      message.warning('请先选择门店');
      return;
    }
    
    setSyncLoading(true);
    try {
      const response = await request('/api/v1/douyin/group/order/sync', {
        method: 'POST',
        data: { store_id: filters.store_id },
      });
      
      if (response.code === 200) {
        message.success('同步成功');
        fetchList();
      } else {
        message.error(response.msg || '同步失败');
      }
    } catch (error) {
      message.error('同步失败');
    } finally {
      setSyncLoading(false);
    }
  };

  // 表格列定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '订单号',
      dataIndex: 'order_id',
      key: 'order_id',
      width: 180,
    },
    {
      title: '门店名称',
      dataIndex: 'store_name',
      key: 'store_name',
      width: 150,
    },
    {
      title: '团购活动',
      dataIndex: 'group_title',
      key: 'group_title',
      width: 200,
    },
    {
      title: '用户信息',
      key: 'user',
      width: 150,
      render: (_, record) => (
        <span>
          {record.user_name}<br />
          {record.user_phone}
        </span>
      ),
    },
    {
      title: '数量',
      dataIndex: 'quantity',
      key: 'quantity',
      width: 80,
    },
    {
      title: '总金额(元)',
      dataIndex: 'total_price',
      key: 'total_price',
      width: 100,
      render: (price) => `¥ ${(price / 100).toFixed(2)}`,
    },
    {
      title: '下单时间',
      dataIndex: 'order_time',
      key: 'order_time',
      width: 180,
      render: (time) => moment(time).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '订单状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => {
        const statusMap = {
          'pending': { text: '待支付', color: 'orange' },
          'paid': { text: '已支付', color: 'green' },
          'completed': { text: '已完成', color: 'blue' },
          'cancelled': { text: '已取消', color: 'red' },
          'refunded': { text: '已退款', color: 'purple' },
        };
        const { text, color } = statusMap[status] || { text: status, color: 'default' };
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '处理状态',
      dataIndex: 'process_status',
      key: 'process_status',
      width: 100,
      render: (status) => {
        const statusMap = {
          'pending': { text: '待处理', color: 'orange' },
          'accepted': { text: '已接单', color: 'green' },
          'rejected': { text: '已拒绝', color: 'red' },
          'completed': { text: '已完成', color: 'blue' },
        };
        const { text, color } = statusMap[status] || { text: status, color: 'default' };
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '使用状态',
      dataIndex: 'is_used',
      key: 'is_used',
      width: 100,
      render: (isUsed) => (
        <Badge status={isUsed === 1 ? 'success' : 'default'} text={isUsed === 1 ? '已使用' : '未使用'} />
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => showDetail(record.id)}
          >
            详情
          </Button>
          {record.process_status === 0 && (
            <>
              <Button
                type="link"
                icon={<CheckOutlined />}
                onClick={() => handleProcess(record.id, 1)}
              >
                接单
              </Button>
              <Button
                type="link"
                danger
                icon={<CloseOutlined />}
                onClick={() => handleProcess(record.id, 2)}
              >
                拒绝
              </Button>
            </>
          )}
          {record.process_status === 1 && (
            <Button
              type="link"
              icon={<CheckCircleOutlined />}
              onClick={() => handleProcess(record.id, 3)}
            >
              完成
            </Button>
          )}
          {record.process_status === 1 && record.is_used === 0 && (
            <Button
              type="link"
              icon={<CheckCircleOutlined />}
              onClick={() => handleUse(record.id)}
            >
              使用券
            </Button>
          )}
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Space>
            <Select
              placeholder="选择门店"
              style={{ width: 200 }}
              onChange={(value) => handleFilterChange({ store_id: value })}
              allowClear
            >
              {douyinConfigs.map(config => (
                <Option key={config.id} value={config.store_id}>
                  {config.store_name}
                </Option>
              ))}
            </Select>
            
            <Select
              placeholder="选择抖音配置"
              style={{ width: 200 }}
              onChange={handleDouyinConfigChange}
              allowClear
            >
              {douyinConfigs.map(config => (
                <Option key={config.id} value={config.id}>
                  {config.store_name} ({config.poi_id})
                </Option>
              ))}
            </Select>
            
            <Select
              placeholder="选择团购活动"
              style={{ width: 200 }}
              value={filters.douyin_group_id}
              onChange={(value) => handleFilterChange({ douyin_group_id: value })}
              allowClear
              disabled={!filters.douyin_id}
            >
              {douyinGroups.map(group => (
                <Option key={group.id} value={group.id}>
                  {group.title}
                </Option>
              ))}
            </Select>
            
            <Select
              placeholder="订单状态"
              style={{ width: 120 }}
              value={filters.status}
              onChange={(value) => handleFilterChange({ status: value })}
              allowClear
            >
              <Option value="pending">待支付</Option>
              <Option value="paid">已支付</Option>
              <Option value="completed">已完成</Option>
              <Option value="cancelled">已取消</Option>
              <Option value="refunded">已退款</Option>
            </Select>
            
            <Select
              placeholder="处理状态"
              style={{ width: 120 }}
              value={filters.process_status}
              onChange={(value) => handleFilterChange({ process_status: value })}
              allowClear
            >
              <Option value="pending">待处理</Option>
              <Option value="accepted">已接单</Option>
              <Option value="rejected">已拒绝</Option>
              <Option value="completed">已完成</Option>
            </Select>
            
            <Select
              placeholder="使用状态"
              style={{ width: 120 }}
              value={filters.is_used}
              onChange={(value) => handleFilterChange({ is_used: value })}
              allowClear
            >
              <Option value={0}>未使用</Option>
              <Option value={1}>已使用</Option>
            </Select>
            
            <RangePicker
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              onChange={(dates) => handleFilterChange({ timeRange: dates })}
            />
            
            <Button
              type="primary"
              icon={<SyncOutlined />}
              onClick={handleSync}
              loading={syncLoading}
            >
              同步订单
            </Button>
          </Space>
        </div>
        
        <Table
          columns={columns}
          dataSource={data}
          rowKey="id"
          loading={loading}
          pagination={{
            current,
            pageSize,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
          }}
          onChange={handleTableChange}
        />
        
        <Modal
          title="订单详情"
          visible={detailVisible}
          onCancel={() => setDetailVisible(false)}
          footer={null}
          width={800}
        >
          {currentOrder && (
            <Descriptions bordered column={2}>
              <Descriptions.Item label="订单号">{currentOrder.order_id}</Descriptions.Item>
              <Descriptions.Item label="门店名称">{currentOrder.store_name}</Descriptions.Item>
              <Descriptions.Item label="团购活动">{currentOrder.group_title}</Descriptions.Item>
              <Descriptions.Item label="用户姓名">{currentOrder.user_name}</Descriptions.Item>
              <Descriptions.Item label="用户电话">{currentOrder.user_phone}</Descriptions.Item>
              <Descriptions.Item label="购买数量">{currentOrder.quantity}</Descriptions.Item>
              <Descriptions.Item label="总金额">{(currentOrder.total_price / 100).toFixed(2)}元</Descriptions.Item>
              <Descriptions.Item label="下单时间">{moment(currentOrder.order_time).format('YYYY-MM-DD HH:mm:ss')}</Descriptions.Item>
              <Descriptions.Item label="订单状态">
                <Tag color={
                  currentOrder.status === 'pending' ? 'orange' :
                  currentOrder.status === 'paid' ? 'green' :
                  currentOrder.status === 'completed' ? 'blue' :
                  currentOrder.status === 'cancelled' ? 'red' :
                  currentOrder.status === 'refunded' ? 'purple' : 'default'
                }>
                  {
                    currentOrder.status === 'pending' ? '待支付' :
                    currentOrder.status === 'paid' ? '已支付' :
                    currentOrder.status === 'completed' ? '已完成' :
                    currentOrder.status === 'cancelled' ? '已取消' :
                    currentOrder.status === 'refunded' ? '已退款' : currentOrder.status
                  }
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="处理状态">
                <Tag color={
                  currentOrder.process_status === 'pending' ? 'orange' :
                  currentOrder.process_status === 'accepted' ? 'green' :
                  currentOrder.process_status === 'rejected' ? 'red' :
                  currentOrder.process_status === 'completed' ? 'blue' : 'default'
                }>
                  {
                    currentOrder.process_status === 'pending' ? '待处理' :
                    currentOrder.process_status === 'accepted' ? '已接单' :
                    currentOrder.process_status === 'rejected' ? '已拒绝' :
                    currentOrder.process_status === 'completed' ? '已完成' : currentOrder.process_status
                  }
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="使用状态">
                <Badge status={currentOrder.is_used === 1 ? 'success' : 'default'} text={currentOrder.is_used === 1 ? '已使用' : '未使用'} />
              </Descriptions.Item>
              <Descriptions.Item label="券码">{currentOrder.voucher_code || '-'}</Descriptions.Item>
              <Descriptions.Item label="券有效期">
                {currentOrder.voucher_valid_time ? moment(currentOrder.voucher_valid_time).format('YYYY-MM-DD HH:mm:ss') : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="使用时间">
                {currentOrder.use_time ? moment(currentOrder.use_time).format('YYYY-MM-DD HH:mm:ss') : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="处理时间">
                {currentOrder.process_time ? moment(currentOrder.process_time).format('YYYY-MM-DD HH:mm:ss') : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="退款状态">
                <Tag color={
                  currentOrder.refund_status === 'pending' ? 'orange' :
                  currentOrder.refund_status === 'success' ? 'green' :
                  currentOrder.refund_status === 'failed' ? 'red' : 'default'
                }>
                  {
                    currentOrder.refund_status === 'pending' ? '退款中' :
                    currentOrder.refund_status === 'success' ? '退款成功' :
                    currentOrder.refund_status === 'failed' ? '退款失败' : currentOrder.refund_status || '-'
                  }
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="备注" span={2}>{currentOrder.remark || '-'}</Descriptions.Item>
              <Descriptions.Item label="抖音备注" span={2}>{currentOrder.douyin_remark || '-'}</Descriptions.Item>
            </Descriptions>
          )}
        </Modal>
      </Card>
    </PageContainer>
  );
};

export default DouyinOrder; 